import { useRoutes, useNavigate, useLocation } from "react-router-dom"
import { useDispatch, useSelector } from "react-redux"
import { useEffect, useMemo } from "react"
import { constantRoutes, asyncRoutes } from "@/views"
import { getInfo } from "@/store/actions"
import { generateRoutes } from "@/store/actions/permission"

// 使用useRoutes来定义路由规则
export default () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const { token, userinfo, accessRoutes } = useSelector(state => state.user)

  useEffect(() => {
    if (token) {
      // 登录流程中、刷新页面时，都要用token获取用户信息
      dispatch(getInfo())
    } else {
      navigate('/login', { replace: true })
    }
  }, [token])

  useEffect(() => {
    // 登录流程中、刷新页面中，使用用户信息动态生成当前用户可以访问的路由规则
    if (userinfo.roles && !accessRoutes.length) {
      // 先生成权限
      dispatch(generateRoutes(asyncRoutes, userinfo.roles))
    }
  }, [userinfo])

  useEffect(() => {
    // 在登录流程中，当路由规则生成完毕，跳转到系统首页
    if (accessRoutes.length && pathname === '/login') {
      navigate('/dashboard', { replace: true })
    }
  }, [accessRoutes])

  useEffect(() => {
    // 没有token，尝试访问非login/(非白名单)页面，跳转到登录页
    if (!token && pathname !== '/login') {
      navigate('/login', { replace: true })
    }
    // 有token(已登录)，尝试访问登录页，跳转到系统首页
    if (token && pathname === '/login') {
      navigate('/dashboard', { replace: true })
    }
    // 有token(已登录)，尝试访问根路径/，跳转到当前用户的首页
    if (token && pathname === '/') {
      navigate('/dashboard', { replace: true })
    }
  }, [pathname])

  // 根据有权限的二级路由，计算得到两层嵌套的路由
  const routes = useMemo(() => {
    let arr = [...constantRoutes]
    arr[0].children = accessRoutes // 来自redux中已生成好的权限路由规则
    return arr
  }, [accessRoutes])

  // console.log('---routes', routes)
  const element = useRoutes(routes) // 动态路由规则
  return element
}

// <Routes>
//   <Route path='/' element={<Layout />}>
//     <Route path='/dashboard' />
//     <Route path='/good/list' />
//   </Route>
//   <Route path='/login' element={<Login />} />
// </Routes>